#coding:utf8
import os
import sys
import struct

fn = sys.argv[1]

con = open(fn, 'rb').read()

class FileCon:
	def ReadInt(self, i):
		num = self.con[i:i+4]
		num = struct.unpack(">L", num)[0]
		#print num
		return i+4, num

	def ReadByte(self, i, l):
		b = self.con[i:i+l]
		#print b
		return i+l, b

	def ReadFileNames(self, i):
		self.fnames = []
		for n in xrange(0, self.fileNum):
			i, num = self.ReadInt(i)
			i, fn = self.ReadByte(i,num)
			self.fnames.append(fn)
		return i

	def IgnoreOffSet(self, i):
		self.fOffset = []
		for n in xrange(0, self.fileNum):
			i, num = self.ReadInt(i)
			self.fOffset.append(num)
		self.fSize = []
		for n in xrange(0, self.fileNum):
			i, num = self.ReadInt(i)
			self.fSize.append(num)
		#return i+self.fileNum*4
		#不明符号
		i += self.fileNum
		return i

	def ReadFileCon(self, i):
		print "ReadFileCon", hex(i)
		print self.fnames
		print map(lambda x: hex(x), self.fOffset)
		print map(lambda x: hex(x), self.fSize)

		self.fCon = []
		for n in xrange(0, self.fileNum):
			print hex(i), n, self.fnames[n]
			i, num = self.ReadInt(i)
			print "fSz", hex(num)
			i, byte = self.ReadByte(i, num)
			#print "nexHead", hex(i)
			self.fCon.append(byte)
			self.WriteFile(n)
		return i

	def WriteFile(self, n):
		global fn
		nfn = fn.replace("/", "_").replace(".", "_")
		dirName = "binFiles/%s" % (nfn)
		if not os.path.exists(dirName):
			os.mkdir(dirName)

		mfn = self.fnames[n].replace("/", "_")
		f = open(dirName+"/"+mfn, "wb")
		f.write(self.fCon[n])
		f.close()

	def Parse(self, con):
		self.con = con
		state = 0
		i = 0
		while i < len(con):
			if state == 0:
				i = 8
				state = 1
			elif state == 1:
				i, num = self.ReadInt(i)
				self.fileNum = num
				state = 2
			elif state == 2: #read fileNameLength
				i = self.ReadFileNames(i)
				state = 3
			elif state == 3: # 
				i = self.IgnoreOffSet(i)
				state = 4
			elif state == 4:
				i = self.ReadFileCon(i)
				state = 5
			else:
				i += 1


fc = FileCon()
fc.Parse(con)


